<template>
  <div class="admin-layout">
    <AdminHeader />
    <div class="main-wrapper">
      <AdminNavbar />
      <div class="content-wrapper">
        <div class="production-line-container">
          <div class="page-header">
            <h2>产线管理</h2>
            <div class="header-actions">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索产品型号"
                clearable
                class="search-input"
                @clear="handleSearch"
                @keyup.enter="handleSearch"
              >
                <template #suffix>
                  <el-icon class="el-input__icon" @click="handleSearch">
                    <Search />
                  </el-icon>
                </template>
              </el-input>
              <el-select v-model="filterStatus" placeholder="状态筛选" clearable @change="handleSearch">
                <el-option label="待生产" value="待生产" />
                <el-option label="生产中" value="生产中" />
                <el-option label="已完成" value="已完成" />
              </el-select>
              <el-button type="primary" @click="openAddDialog">
                <el-icon><Plus /></el-icon> 添加产线
              </el-button>
            </div>
          </div>

          <!-- 产线列表 -->
          <el-table :data="productionLines" border style="width: 100%" v-loading="loading">
            <el-table-column prop="lineId" label="产线ID" width="80" />
            <el-table-column prop="productModel" label="产品型号" width="150" />
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="开始时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.startTime) }}
              </template>
            </el-table-column>
            <el-table-column label="结束时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.endTime) || '未结束' }}
              </template>
            </el-table-column>
            <el-table-column label="创建时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.createdAt) }}
              </template>
            </el-table-column>
            <el-table-column label="更新时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.updatedAt) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="500" scope.row.status>
              <template #default="scope">
                <el-button size="small" type="primary" @click="handleEdit(scope.row)" :disabled="scope.row.status !== '待生产'">
                  <el-icon><Edit /></el-icon> 编辑
                </el-button>
                <el-button size="small" type="success" @click="viewTasks(scope.row)" :disabled="scope.row.status !== '待生产'">
                  <el-icon><View /></el-icon> 查看工序
                </el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.row)" :disabled="scope.row.status !== '待生产'">
                  <el-icon><Delete /></el-icon> 删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑产线对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑产线' : '添加产线'"
      width="500px"
      destroy-on-close
    >
      <el-form :model="lineForm" :rules="rules" ref="lineFormRef" label-width="100px">
        <el-form-item label="产品型号" prop="productModel">
          <el-input v-model="lineForm.productModel" placeholder="请输入产品型号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看工序对话框 -->
    <el-dialog
      v-model="tasksDialogVisible"
      title="产线工序列表"
      width="800px"
    >
      <div v-if="currentLine" class="line-info">
        <h3>产线 {{ currentLine.lineId }} - {{ currentLine.productModel }}</h3>
        <p>状态: <el-tag :type="getStatusType(currentLine.status)">{{ currentLine.status }}</el-tag></p>
      </div>

      <el-table :data="processTasks" border style="width: 100%" v-loading="tasksLoading">
        <el-table-column prop="taskId" label="工序ID" width="80" />
        <el-table-column prop="processName" label="工序名称" width="120" />
        <el-table-column label="状态" width="300">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewEquipments(scope.row)">
              <el-icon><List /></el-icon> 查看设备
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-if="processTasks.length === 0 && !tasksLoading" class="no-tasks">
        <el-empty description="该产线暂无工序" />
      </div>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="删除确认"
      width="400px"
    >
      <div class="delete-confirm">
        <el-icon class="warning-icon"><Warning /></el-icon>
        <p>确定要删除产线 "{{ currentLine?.lineId }}" 吗？此操作不可恢复。</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 设备详情对话框 -->
    <el-dialog
      v-model="equipmentsDialogVisible"
      title="工序设备详情"
      width="80%"
    >
      <div v-if="currentTask" class="task-detail">
        <div class="task-info-header">
          <h3>{{ currentTask.processName }} (工序区 #{{ currentTask.taskId }})</h3>
          <el-tag :type="getStatusType(currentTask.status)">{{ currentTask.status }}</el-tag>
        </div>

        <el-descriptions :column="3" border>
          <el-descriptions-item label="所属生产线">{{ currentTask.lineId }}</el-descriptions-item>
          <el-descriptions-item label="产品型号">{{ currentTask.productModel }}</el-descriptions-item>
          <el-descriptions-item label="工序状态">{{ taskStatus(currentTask.status) }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(currentTask.createdAt) }}</el-descriptions-item>
        </el-descriptions>

        <!-- 设备列表 -->
        <div class="equipment-section">
          <h3>设备列表</h3>
          <el-empty v-if="!currentTask.equipmentList || currentTask.equipmentList.length === 0" description="暂无设备数据" />
          <div v-else class="equipment-grid">
            <el-card v-for="equipment in currentTask.equipmentList" :key="equipment.equipmentId" class="equipment-card" :class="getEquipmentStatusClass(equipment.status)">
              <div class="equipment-header">
                <div class="equipment-title">
                  <el-icon><Cpu /></el-icon>
                  <span>{{ equipment.name }}</span>
                </div>
                <el-tag :type="getEquipmentStatusType(equipment.status)" size="small">{{ equipment.status }}</el-tag>
              </div>
              <div class="equipment-details">
                <div class="detail-item">
                  <span class="detail-label">设备类型:</span>
                  <span class="detail-value">{{ equipment.type }}</span>
                </div>
                <div class="detail-item">
                  <span class="detail-label">当前温度:</span>
                  <span class="detail-value">{{ equipment.currentTemp }}°C</span>
                </div>
                <div class="detail-item">
                  <span class="detail-label">温度阈值:</span>
                  <span class="detail-value">{{ equipment.tempThreshold }}°C</span>
                </div>
                <div class="temp-progress">
                  <el-progress
                    :percentage="getTempPercentage(equipment.currentTemp, equipment.tempThreshold)"
                    :status="getTempStatus(equipment.currentTemp, equipment.tempThreshold)"
                    :stroke-width="10"
                    :format="(percentage) => `${equipment.currentTemp}°C / ${equipment.tempThreshold}°C`"
                  />
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
    getProductionLines,
    getProductionLineById,
    getProcessTaskById,
    updateProductionOrder,
    addProductionOrder, addProductionLine, updateProductionLine, deleteProcessLine
} from '@/api/production'
import AdminHeader from '@/components/AdminHeader.vue'
import AdminNavbar from '@/components/AdminNavbar.vue'
import { Search, Plus, Edit, Delete, View, Warning, List, Cpu } from '@element-plus/icons-vue'

// 数据定义
const productionLines = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('')
const filterStatus = ref('')
const dialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const tasksDialogVisible = ref(false)
const equipmentsDialogVisible = ref(false)
const isEdit = ref(false)
const currentLine = ref(null)
const currentTask = ref(null)
const processTasks = ref([])
const tasksLoading = ref(false)
const lineFormRef = ref(null)

// 表单数据
const lineForm = reactive({
  lineId: null,
  productModel: '',
  status: '待生产',
  startTime: null,
  endTime: null
})

// 表单验证规则
const rules = {
  productModel: [
    { required: true, message: '请输入产品型号', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择产线状态', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ]
}

// 获取产线列表
const fetchProductionLines = async () => {
  loading.value = true
  try {
    const res = await getProductionLines({
      current: currentPage.value,
      size: pageSize.value,
      keyword: searchKeyword.value,
      status: filterStatus.value
    })

    if (res.success) {
      productionLines.value = res.data.records || res.data
      total.value = res.data.total || res.data.length
    } else {
      ElMessage.error(res.message || '获取产线列表失败')
    }
  } catch (error) {
    ElMessage.error('获取产线列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchProductionLines()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchProductionLines()
}

// 当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchProductionLines()
}

// 打开添加对话框
const openAddDialog = () => {
  isEdit.value = false
  Object.assign(lineForm, {
    lineId: null,
    productModel: '',
    status: '待生产',
    startTime: null,
    endTime: null
  })
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(lineForm, {
    lineId: row.lineId,
    productModel: row.productModel,
    status: row.status,
    startTime: row.startTime ? new Date(row.startTime) : null,
    endTime: row.endTime ? new Date(row.endTime) : null
  })
  dialogVisible.value = true
}

// 查看工序
const viewTasks = async (row) => {
  currentLine.value = row
  tasksDialogVisible.value = true
  tasksLoading.value = true

  try {
    const res = await getProductionLineById(row.lineId)
    if (res.success) {
      processTasks.value = res.data.processTaskList || []
    } else {
      ElMessage.error(res.message || '获取工序列表失败')
      processTasks.value = []
    }
  } catch (error) {
    ElMessage.error('获取工序列表失败')
    processTasks.value = []
  } finally {
    tasksLoading.value = false
  }
}

// 查看设备
const viewEquipments = async (task) => {
  try {
    const res = await getProcessTaskById(task.taskId)
    if (res.success) {
      currentTask.value = res.data
      equipmentsDialogVisible.value = true
    } else {
      ElMessage.error(res.message || '获取设备列表失败')
    }
  } catch (error) {
    ElMessage.error('获取设备列表失败')
  }
}

// 工序状态显示
const taskStatus = (status) => {
  if (status === "生产中") {
    return "运行中"
  }
  return "未运行"
}

// 获取温度百分比
const getTempPercentage = (current, threshold) => {
  if (!current || !threshold) return 0
  return Math.min(Math.round((current / threshold) * 100), 100)
}

// 获取温度状态
const getTempStatus = (current, threshold) => {
  if (!current || !threshold) return ''
  if (current > threshold * 1.1) return 'exception'
  if (current > threshold) return 'warning'
  return 'success'
}

// 获取设备状态类型
const getEquipmentStatusType = (status) => {
  switch (status) {
    case '运行':
      return 'success'
    case '维修':
      return 'warning'
    case '停机':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取设备状态样式类
const getEquipmentStatusClass = (status) => {
  switch (status) {
    case '运行':
      return 'equipment-normal'
    case '维修':
      return 'equipment-maintenance'
    case '停机':
      return 'equipment-fault'
    default:
      return ''
  }
}

// 打开删除确认对话框
const handleDelete = (row) => {
  currentLine.value = row
  deleteDialogVisible.value = true
}

// 确认删除
const confirmDelete = async () => {
  try {
      await deleteProcessLine(currentLine.value.lineId)
      deleteDialogVisible.value = false
      await fetchProductionLines()
  } catch (error) {
    ElMessage.error('删除产线失败')
  }
}

// 提交表单
const submitForm = async () => {
  if (!lineFormRef.value) return

  await lineFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
          let res;
          if (isEdit.value) {
              // 编辑订单
              res = await updateProductionLine(lineForm);
          } else {
              // 添加订单
              res = await addProductionLine(lineForm);
          }

          if (res.success) {
              const message = isEdit.value ? '编辑' : '添加';
              ElMessage.success(`生产线${message}成功`);
              dialogVisible.value = false;
              fetchProductionLines();
          } else {
              ElMessage.error(res.message || `订单${isEdit.value ? '编辑' : '添加'}失败`);
          }
      } catch (error) {
        ElMessage.error(`产线${isEdit.value ? '编辑' : '添加'}失败`)
      }
    }
  })
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case '生产中':
      return 'success'
    case '未开始':
      return 'info'
    case '已完成':
      return ''
    default:
      return 'info'
  }
}

// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return ''
  return new Date(datetime).toLocaleString()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchProductionLines()
})
</script>

<style scoped>
.admin-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7f9;
}

.main-wrapper {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.content-wrapper {
  flex: 1;
  padding: 24px;
  overflow: auto;
  background: #fff;
  margin: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.production-line-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 250px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.line-info {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.no-tasks {
  padding: 30px 0;
}

.delete-confirm {
  display: flex;
  align-items: center;
  gap: 10px;
}

.warning-icon {
  font-size: 24px;
  color: #F56C6C;
}

/* 设备详情样式 */
.task-detail {
  padding: 20px 0;
}

.task-info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.equipment-section {
  margin-top: 30px;
}

.equipment-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.equipment-card {
  border-radius: 8px;
  transition: all 0.3s;
}

.equipment-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.equipment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.equipment-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: bold;
}

.equipment-details {
  margin-top: 10px;
}

.detail-item {
  display: flex;
  margin-bottom: 8px;
}

.detail-label {
  width: 80px;
  color: #606266;
}

.detail-value {
  font-weight: 500;
}

.temp-progress {
  margin-top: 15px;
}

.equipment-normal {
  border-left: 4px solid #67C23A;
}

.equipment-maintenance {
  border-left: 4px solid #E6A23C;
}

.equipment-fault {
  border-left: 4px solid #F56C6C;
}
</style>
